#author : zhangruonan
import numpy as np
import cv2
import glob

# extract object points and image points
objp = np.zeros((8*6, 3), np.float32)
objp[:, :2] = np.mgrid[0:8, 0:6].T.reshape(-1, 2)
print(objp.shape)

# Arrays to store object points and image points from all the images.
objpoints = []   
imgpoints = []   

images = glob.glob('./test_image/*.jpg')
print(len(images))

# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (8, 6), None)    
    if ret == True:
        objpoints.append(objp)
        imgpoints.append(corners)

        # Draw and display the corners
        cv2.drawChessboardCorners(img, (8, 6), corners, ret)
        cv2.imshow('img', img)
        cv2.waitKey(50)

# calibrate
img = cv2.imread('/home/jk/Video_out/video/485.jpg')
img_size = (img.shape[1], img.shape[0])
print(len(objpoints))
# Do camera calibration given objects points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
print(mtx,dist)

dst = cv2.undistort(img, mtx, dist, None, mtx)   
cv2.imwrite('test_undist.jpg', dst)

